package service

import (
	"context"

	"github.com/go-kit/kit/endpoint"
	"golang.org/x/time/rate"
	"errors"
	"github.com/go-kit/kit/log"
)

type UserRequest struct{
	Uid int `json:"uid"`
	Method string `json:"method"`
}

type UserResponse struct{
	Result string `json:"result"`
}

//日志中间件,每一个service都应该有自己的日志中间件
func UserServiceLogMiddleware(logger log.Logger) endpoint.Middleware { //Middleware type Middleware func(Endpoint) Endpoint
    return func(next endpoint.Endpoint) endpoint.Endpoint { //Endpoint type Endpoint func(ctx context.Context, request interface{}) (response interface{}, err error)
        return func(ctx context.Context, request interface{}) (response interface{}, err error) {
            r := request.(UserRequest) //通过类型断言获取请求结构体
            logger.Log("method", r.Method, "event", "get user", "userid", r.Uid)
            return next(ctx, request)
        }
    }
}

//限流
func RateLimit(limit *rate.Limiter) endpoint.Middleware{
	return func (next endpoint.Endpoint) endpoint.Endpoint{
		return func(ctx context.Context, request interface{}) (response interface{}, err error){
			if !limit.Allow(){
				return nil, errors.New("too many request")
			}
			return next(ctx, request)
		}
	}
}

func GetUserEnpoint(usi UserServiceIf) endpoint.Endpoint{
	return func(ctx context.Context, request interface{}) (response interface{}, err error){
		r := request.(UserRequest)
		result := ""
		if r.Method == "GET"{
			result = usi.GetName(r.Uid)
		}else if r.Method == "DELETE"{
			err := usi.DelUser(r.Uid)
			if err != nil{
				result = err.Error()
			}else{
				result = "删除成功"
			}
		}
		return UserResponse{Result: result}, nil
	}
}
